//监控类型
const camtypes = {
	rtc: "rtc", //rtsp
	flv_hls: "flv_hls",
}

//当前使用类型
const use = camtypes.rtc;

/**
 * ----------------------------------- rtc    --------------------
 */
var videoRtcIsDone = false;

function hWaitWebRtc() {

	if (typeof(WebRtcPlayer) != typeof(undefined) && !videoRtcIsDone) {
		WebRtcPlayer.setServer('127.0.0.1:8083');
		console.log("WebRtcPlayer done.");
		videoRtcIsDone = true;
	} else {
		setTimeout(function() {
			hWaitWebRtc();
		}, 3000);
	}
}

function createVideoDom(id) {
	id = id || "cam_" + Date.now();
	// <button class="camClose" onclick="ClosePanel('${id}')"> X </button>
	// var html = `<video class="videoPlayer" id="v1_${id}" autoplay muted ></video> `;
	var html = `<button class="camClose" style="font-size: 20px;color: red;position: absolute;z-index: 1;right: 0;" onclick="ClosePanel('${id}')"> X </button><video style="width: 100%;height: 100%;object-fit: fill;" class="videoPlayer" id="v1_${id}" autoplay muted ></video> `;
	var doms = document.createElement("div");
	doms.setAttribute("id", id);
	doms.setAttribute("class", 'panel');
	doms.innerHTML = html;
	document.body.appendChild(doms);
	return doms;
}
//rtsp://admin:aa123456@192.168.1.68/Streaming/Channels/101?transportmode=unicast
/**
 * ----------------------------flv      hls        ----------------------
 */

//var hlsTemplate="http://{0}:7086/live/cameraid/{1}%24{2}/substream/{3}.m3u8";
//var hlsHttpsTemplate="https://{0}:7096/live/cameraid/{1}%24{2}/substream/{3}.m3u8";
//var flvTemplate="http://{0}:7886/live/cameraid/{1}%24{2}/substream/{3}.flv";
//var flvHttpsTemplate="https://{0}:7896/live/cameraid/{1}%24{2}/substream/{3}.flv";
//var flv = String.format(flvTemplate, ip, deviceCode, channelSeq, sustreamType);
String.format = function(src) {
	if (arguments.length == 0) return null;
	var args = Array.prototype.slice.call(arguments, 1);
	return src.replace(/\{(\d+)\}/g, function(m, i) {
		return args[i];
	});
};
var flvhls = false;
var _wh = -1;

function hWaitFlvHls() {
	if (typeof(flvjs) != typeof(undefined) || typeof(Hls) != typeof(undefined)) {
		clearTimeout(_wh);
		flvhls = true;
	} else {
		_wh = setTimeout(function() {
			hWaitFlvHls();
		}, 3000);
	}
}



function ShowPanel(id) {
	var dom = document.querySelector("#" + id);
	// dom.setAttribute("style", "display:block;");
	dom.setAttribute("style", "display:block;position: absolute;width: 40vw;height: 26vw;top: calc(50vh - 13vw);left: calc(50vw - 20vw);background: rgba(0, 0, 0, .5);");
}

function ClosePanel(id) {
	var dom = document.querySelector("#" + id);
	dom.setAttribute("style", "display:none;");

	hClearFlvHls();
	if (typeof(__hToUnity) != 'undefined') {

		for (var i = 0; i < v2s.length; i++) {
			v2s[i].destroy();
		}
		for (var i = 0; i < players.length; i++) {
			players[i].video.destroy();
		}


		__hToUnity.SetCamSelectUpdateDisable();
	}
}

window.players = [];


/**
 * @param {Object} id dom id
 * @param {Object} p {x:0,y:0}
 */
function SetPos(id, p) {
	var dom = document.querySelector("#" + id);
	var t = `left:${p.x}px;top:${p.y}px`;
	//`transform: translate();`
	dom.setAttribute("style", t);
}

function PlayVideo(vDomId, camCode, host) {
	var id = "v1_" + vDomId;
	var dom = document.querySelector("#" + id);
	if (!dom) {
		dom = createVideoDom(id);
		if (typeof(hMouseDown) != 'undefined')
			dom.addEventListener("mousedown", hMouseDown, false);
	}
	ShowPanel(id);
	if (flvhls) { 
		dom = document.querySelector("#" + id);
		hHlsPlay(host, camCode, dom);
		console.error("未完善");
		return dom;
	}
	var v = players.find((t) => t.id == id);
	if (!v) {
		if (host) {
			WebRtcPlayer.setServer(host);
		}
		var wv = new WebRtcPlayer("v1_" + id, 'demo');
		v = {
			id: id,
			video: wv
		};
		players.push(v);

	}
	if (camCode) {
		try {
			v.video.load(camCode);
		} catch (e) {
			//TODO handle the exception
		}
	}
	return dom;
}
var v2s = [];
/**
 * @param {Object} dats [{id:0,code:""}]
 * @param {Object} host ip
 */
function PlayVideos(dats, host) {
	if (!dats || dats.length <= 0)
		return;
	hClearFlvHls();
	if (dats.length == 1) {
		var dat = dats[0];
		PlayVideo(dat.id, dat.code, host);
		return;
	}
	var pid = "mcams";
	var dom = document.querySelector("#" + pid);
	var box;
	if (!dom) {
		dom = createVideoDom(pid);
		if (typeof(hMouseDown) != 'undefined')
			dom.addEventListener("mousedown", hMouseDown, false);
		//dom.lastChild().remove(true);
		dom.children[1].remove();
		box = document.createElement("div");
		box.setAttribute("class", 'panels');
		dom.appendChild(box);
	} else {
		box = dom.children[1];
	}

	var vhtml = "";
	for (var i = 0; i < dats.length; i++) {
		var dat = dats[i];
		vhtml += `<div>
					<video id="v2_${dat.id}" class="videoPlayer" autoplay muted></video>
					<label>cam_${dat.id}</label>
				</div>`;
	}
	box.innerHTML = vhtml;
	ShowPanel(pid);

	for (var i = 0; i < dats.length; i++) {
		var dat = dats[i];

		if (flvhls) {
			var domvideo = document.querySelector("#v2_" + dat.id);
			hHlsPlay(host, dat.code, domvideo);
		} else {
			var v2 = new WebRtcPlayer("v2_" + dat.id, 'demo');
			var v3 = {
				id: dat.id,
				video: v2
			};
			v2s.push(v2);
			v2.load(dat.code);
		}
	}

}

function hHlsPlay(ip, channelCode, domVideo) {
	var hlsTemplate = "http://{0}:7086/live/cameraid/{1}%24{2}/substream/{3}.m3u8";

	ip = ip || "192.168.100.2";
	if (!channelCode) {
		console.warn("监控打开失败。编码异常。" + channelCode);
		return;
	}
	//var channelCode=$("#channelCode").val();
	var deviceCode = channelCode.substr(0, channelCode.indexOf("$"));
	var channelSeq = channelCode.substr(channelCode.lastIndexOf("$") + 1);
	var sustreamType = 1; //1主码流，2辅码流
	var hls = String.format(hlsTemplate, ip, deviceCode, channelSeq, sustreamType);

	play(hls, domVideo);
}

function isHlsFlv(url) {
	var extension = url.substring(url.lastIndexOf('.') + 1);

	if ("m3u8" == extension.toLowerCase()) {
		return "hls";
	}
	if ("flv" == extension.toLowerCase()) {
		return "flv";
	}
	return "";
}
var _flvps = [],
	_hlsps = [];

function play(url, domVideo) {


	if ('hls' == isHlsFlv(url)) {
		var hlsPlayer = new Hls();
		hlsPlayer.loadSource(url);
		hlsPlayer.attachMedia(domVideo);
		hlsPlayer.on(Hls.Events.MANIFEST_PARSED, function() {
			domVideo.play();
		});
		_hlsps.push(hlsPlayer);
	} else if ('flv' == isHlsFlv(url)) {
		var flvPlayer = flvjs.createPlayer({
			type: 'flv',
			url: url
		});
		flvPlayer.attachMediaElement(domVideo);
		flvPlayer.load();
		flvPlayer.play();
		_flvps.push(flvPlayer);

	} else {

		console.log("错误类型地址")
	}
}

function hClearFlvHls() {
	for (var i = 0; i < _flvps.length; i++) {
		var f = _flvps[i];
		f.unload();
		f.detachMediaElement();
		f.destroy();
		f = null;
	}
	for (var i = 0; i < _hlsps.length; i++) {
		var h = _hlsps[i];
		h.destroy();
	}
}


switch (use) {
	case camtypes.rtc:
		hWaitWebRtc();
		break;
	case camtypes.flv_hls:
		hWaitFlvHls();
		break;
	default:
		break;
}